package com.levenx.utils;

import java.io.File;
import java.io.IOException;

public class FileUtils {

    private static final char WINDOWS_SEPARATOR = '\\';

    private static final char SYSTEM_SEPARATOR;

    public static long sizeOf(File file){
        if(!file.exists()){
            return 0L;
        }else {
            return file.isDirectory() ? sizeOfDirectory(file) : file.length();
        }
    }

    private static long sizeOfDirectory(File directory) {
//        checkDirectory(directory);
        File[] files = directory.listFiles();
        if(files == null){
            return 0L;
        }else {
            long size = 0L;
            int length = files.length;

            for(int i=0; i<length; i++){
                File file = files[i];
                try {
                    if(!isSymlink(file)){
                        size += sizeOf(file);
                        if(size < 0L) {
                            break;
                        }
                    }
                }catch (IOException e){

                }
            }
            return size;
        }
    }

    private static boolean isSymlink(File file) throws IOException {
        if(file == null){
            throw new NullPointerException("file null");
        }else if(SYSTEM_SEPARATOR == 92){
            return false;
        }else {
            File fileInCanonicalDir = null;
            if(file.getParent() == null){
                fileInCanonicalDir = file;
            }else {
                File canonicalDir = file.getParentFile().getCanonicalFile();
                fileInCanonicalDir = new File(canonicalDir,file.getName());
            }
            return !fileInCanonicalDir.getCanonicalFile().equals(fileInCanonicalDir.getAbsoluteFile());
        }
    }

//    private static void checkDirectory(File directory) throws IllegalAccessException {
//        if(!directory.exists()){
//            throw new IllegalAccessException(directory + " miss");
//        }else if(!directory.isDirectory()){
//            throw new IllegalAccessException(directory + " is not a directory");
//        }
//    }


    static {
        SYSTEM_SEPARATOR = File.separatorChar;
    }

}
